package com.yinzifan.seller.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.yinzifan.api.ProductRpc;
import com.yinzifan.api.domain.ProductRpcReq;
import com.yinzifan.entity.Product;
import com.yinzifan.entity.enums.ProductStatus;
@Component
public class ProductCache {
	private static final String CACHE_NAME="product";
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductCache.class);

	@Autowired
	private ProductRpc productRpc;
	
	@Autowired
	private HazelcastInstance hazelcastInstance;
	/**
	 * 读取缓存
	 * @param id
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Product> readAllCache() {
		IMap map = hazelcastInstance.getMap(CACHE_NAME);
		List<Product> products = null;
		if(map.size() > 0) {
			products = new ArrayList<>(); 
			products.addAll(map.values());
		} else {
			products = findAll();
		}
		return products;
	}
	private List<Product> findAll() {
		ProductRpcReq req = new ProductRpcReq();
		List<String> status = new ArrayList<>();
		status.add(ProductStatus.IN_SELL.name());
		req.setStatusList(status);
		LOGGER.info("rpc查询全部产品, 参数: {}", req.toString());
		List<Product> result = productRpc.query(req);
		LOGGER.info("rpc查询全部产品, 结果: {}", result);
		return result;
	}
	
	
	@Cacheable(cacheNames=CACHE_NAME)
	public Product readCache(String id) {
		LOGGER.info("rpc查询一个产品, 参数: {}", id);
		Product result = productRpc.findOne(id);
		LOGGER.info("rpc查询一个产品, 结果: {}", result);
		return result;
	}
	@CachePut(cacheNames=CACHE_NAME, key="#product.id")
	public Product putCache(Product product) {
		return product;
	}
	@CacheEvict(cacheNames=CACHE_NAME, key="#product.id")
	public void removeCache(String id) {
	}
}
